package com.atguigu.chapter06;

import com.atguigu.bean.MarketingUserBehavior;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.util.Random;

/**
 * Author: Pepsi
 * Date: 2023/7/31
 * Desc:
 */
public class Flink04_Project_App {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        // 统计不同的渠道不同的行为的个数
        env
                // 从自定义数据源读取数据
                .addSource(new AppSource())
                // 将市场用户行为映射为元组 (oppo_install,1)
                .map(new MapFunction<MarketingUserBehavior, Tuple2<String,Long>>() {
                    @Override
                    public Tuple2<String, Long> map(MarketingUserBehavior value) throws Exception {
                        System.out.println(value);
                        return Tuple2.of(value.getChannel()+"_"+value.getBehavior(),1L);
                    }
                })
                // 以渠道和行为进行分组
                .keyBy(new KeySelector<Tuple2<String, Long>, String>() {
                    @Override
                    public String getKey(Tuple2<String, Long> value) throws Exception {
                        return value.f0;
                    }
                })
                // 求和
                .sum(1)
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class AppSource implements SourceFunction<MarketingUserBehavior> {

        @Override
        public void run(SourceContext<MarketingUserBehavior> ctx) throws Exception {

            Random random = new Random();
            String [] behaviors = {"download","install","update","uninstall"};
            String [] channels = {"Appstore","huawei","vivo","oppo","xiaomi"};


            while (true){

                Long userId = (long)(random.nextInt(2000) + 1);
                String behavior = behaviors[random.nextInt(behaviors.length)];
                String channel = channels[random.nextInt(channels.length)];
                Long timestame = System.currentTimeMillis();

                ctx.collect(
                        new MarketingUserBehavior(
                                userId,
                                behavior,
                                channel,
                                timestame
                        ));
                Thread.sleep(200);
            }
        }

        @Override
        public void cancel() {

        }
    }
}
